
const https = require('https');
const querystring = require('querystring');

exports.ajax = (config) => {
    return new Promise((resolve) => {
        const {
            host, 
            path, 
            param, 
            data, 
            method, 
            headers
        } = config;
        console.log(`${path}?${param ? querystring.stringify(param) : ''}`)
        const request = https.request({
            hostname: host,
            path: `${path}?${param ? querystring.stringify(param) : ''}`,
            method: method == 'POST' ? 'POST' : 'GET',
            headers: Object.assign({},{
                'Content-Type': 'application/json; charset=UTF-8'
            },headers || {}),
        },(response) => {
            let data = '';
            response.on('data', s => data+=s);
            response.on('end', () => {
                try {
                    resolve({
                        result : 0,
                        data : JSON.parse(data)
                    });
                }catch (e){
                    resolve({
                        result : -100,
                    });
                }
            });
        });
        if(method == 'POST'){
            request.write(JSON.stringify(data));
        }
        request.end();
    });
};